from os import path
import urlparse
import urllib2
import libxml2
import libxslt
import RDF

__all__ = ["transform", "parse"]

from mx.DateTime import DateTimeFrom, DateTimeDeltaFrom
oneDay = DateTimeDeltaFrom("1 day") - DateTimeDeltaFrom("1 second")
def thredds_addOneDay(ctx, start, end):
    start = DateTimeFrom(start)
    end = DateTimeFrom(start)
    if start == end:
        return str(end + oneDay)
    else:
        return str(end)
libxslt.registerExtModuleFunction("addOneDay",
                  "http://catalog.terradue.com/schemas/thredds.xsl#",
                  thredds_addOneDay)

def stylesheet(name):
    thredds_dir = path.dirname(path.realpath(__file__))
    filename = path.join(thredds_dir, "xsl", name)
    styledoc = libxml2.parseFile(filename)
    style = libxslt.parseStylesheetDoc(styledoc)
    return style

def transform(uri, format=False,urlbase=None):
    fp = urllib2.urlopen(uri)
    data = fp.read()
    fp.close()

    scheme, netloc, path, query, frag = urlparse.urlsplit(uri)
    if urlbase is None:
        urlbase = scheme + "://" + netloc
    
    doc = libxml2.parseDoc(data)
    style = stylesheet("thredds_rdf.xsl")
    result = style.applyStylesheet(doc,
                       { "product_uri" : "'" + uri + "'",
                     "base_uri" : "'" + urlbase + "'" })

    rdfxml = result.serialize("utf-8", format)
    

    style.freeStylesheet()
    result.freeDoc()
    doc.freeDoc()

    return rdfxml

def parse(uri):
    """
    >>> code_dir = path.dirname(path.realpath(__file__))
    >>> test_file = path.join(code_dir, "..", "..", "examples", "nrt_v1.xml")
    >>> model = parseURI("file://" + test_file)
    >>>
    >>> uri = "http://fe4.sic.rm.cnr.it:8080/thredds/config/SST/NRT/V1/NOT_AGGR/nrt_v1.xml"
        >>> model = parseURI(uri)
    >>>
    """
    rdfxml = transformURI(uri)
    storage = RDF.Storage(storage_name="memory", name=uri, options_string="")
    model = RDF.Model(storage)
    parser = RDF.Parser()
    parser.parse_string_into_model(model, rdfxml, uri)
    return model

if __name__ == '__main__':
    import doctest
    doctest.testmod()
